﻿using DotNetCore.CAP;
using EF.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OrderService.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrderController : ControllerBase
    {
        /// <summary>
        /// cap发布对象
        /// </summary>
        public ICapPublisher CapPublisher { get; set; }
        /// <summary>
        /// 数据库连接
        /// </summary>
        public CommonContext Db { get; set; }
        /// <summary>
        /// 配置文件
        /// </summary>
        public IConfiguration Configuration { get; set; }

        /// <summary>
        /// mysql连接字符串
        /// </summary>
        public string MySqlConStr { get; set; }

        public OrderController(ICapPublisher CapPublisher, CommonContext dbContext, IConfiguration configuration)
        {
            this.CapPublisher = CapPublisher;
            this.Db = dbContext;
            this.Configuration = configuration;
            this.MySqlConStr = configuration["CapSetting:MySqlConStr"];
        }


        [NonAction]
        [CapSubscribe("User_Apply_Order_Publish_Message")]
        public async Task ReciveApplyMessage(Payment payment, [FromCap] CapHeader header)//body和header
        {
            var dbOrder = await Db.Order.FirstOrDefaultAsync(e => e.Id == payment.OrderId);
            if (dbOrder == null)
            {
                //TODO:数据异常
                return;
            }
            if (dbOrder.OrderStatus > 0)
            {
                //订单已经被支付了，重复消息，跳过
                return;
            }
            dbOrder.OrderStatus = 1;
            await Db.SaveChangesAsync();
            Console.WriteLine($"==============================更新订单：【{dbOrder.Id}】状态成功，来源于订单：【{payment.Id}】==============================");
        }
    }
}
